<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_block_DuplicatePageAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
		$originalPage = $this->getDocumentProvider()->getByUniqueId($this->getRequestParameter("docId"), $this->getRequestParameter("docLang"));
		$formValues = $this->getFormValues("form");

        $errors = array();

		if(count($formValues) > 0)
		{
			if($formValues['label'] == "")
			{
				$errors["label"] = $this->getLocale('website.errors.required');
			}
			else
			{
                $parent = $this->getDocumentProvider()->getByUniqueId($formValues['folder']);
				$destPage = $this->duplicatePage($formValues, $originalPage, $parent);
				$this->addToModel("destPage", $destPage);
				$errors["status"] = "success";
			}
		}
		else
		{
			$values["label"]   = $originalPage->getLabel()." ( copie )";
            //$values["folders"] = $this->createArbo();
            $values["folders"] = m_backoffice_services_TreeService::getInstance()->getSelectArray($this->getContextWebsite()->getUniqueId(), array("modules_website/menu"), $this->getContextWebsite()->getUniqueId(), true, true, 'website');
            $values["folder"]  = $originalPage->getDocumentParent()->getUniqueId();
		}
		
		$this->addToModel("errors", $errors);
		$this->addToModel("href", $this->getRequestParameter("href"));
		$this->addToModel("formValues", $values);
		$this->addToModel("originalPage", $originalPage);
		$this->setView('success');
	}
	
	public function validate()
	{
        return $this->getUserContext()->hasRight(array("backoffice_accessBo", "website_Edit"));
	}

    private function createArbo($idMenu=null,$rec=0)
    {
        $tabRet = array();
        if($idMenu==null)
        {
            $websites = $this->getDocumentProvider()->loadDocuments("modules_website/website")->retrieveDocuments();
            foreach($websites as $website)
            {
                $temp['id']    = $website->getUniqueId();
                $temp['label'] = $temp['titre'] = $website->getLabel();
                $tabRet[]      = $temp;
                $arbo = $this->createArbo($website->getUniqueId(),$rec+1);
                if(count($arbo)>0)
                    $tabRet = array_merge($tabRet,$arbo);
            }
        }
        else
        {
            $topString = "";
            for($i=0;$i<$rec;$i++){$topString.="&nbsp;&nbsp;";}
            $menus = $this->getDocumentProvider()->getByUniqueId($idMenu)->getMenus();
            foreach($menus as $menu)
            {
                $temp['id']    = $menu->getUniqueId();
                $temp['label'] = $topString.$menu->getLabel();
                $temp['titre'] = $menu->getLabel();
                $tabRet[]      = $temp;
                $arbo = $this->createArbo($menu->getUniqueId(),$rec+1);
                if(count($arbo)>0)
                    $tabRet = array_merge($tabRet,$arbo);
            }
        }
        return $tabRet;
    }
	
	private function duplicatePage($formValues, $originalPage,$parent=null)
	{
        /* @var $originalPage m_website_documents_page */
		$destPage = $originalPage->cloneToNew();
		$destPage->save(false);
                
		if($parent==null)
        {
            $parent = $this->getParent($originalPage);
        }

        if($parent instanceof m_website_documents_Menu || $parent instanceof m_website_documents_Website)
        {
            $newUrl = preg_match("#/$#",$parent->getUrl()) ? $parent->getUrl() : $parent->getUrl()."/" ;
            preg_match("#/([^/]*)$#",$destPage->getUrl(),$match);

            $newUrl = $newUrl.$match[1];

            $newUrl = str_replace('http://'.$originalPage->getWebsite()->getRealUrl(), '', $newUrl);

            $destPage->setUrl($newUrl);
        }
                
		$content = $destPage->getAllBlocks();
			
		foreach($content as $block)
		{
			if(isset($block["contentId"]))
			{
				$linkContent = $this->getDocumentProvider()->getByUniqueId($block["contentId"], $originalPage->getLang());
				$newContent = $linkContent->cloneToNew();
				$newContent->save(false);				
				$block["contentId"] = $newContent->getUniqueId();
			}
			
			if(isset($block["pageId"]))
			{
				$block["pageId"] = $destPage->getUniqueId();
			}
			
			if(isset($block["revision"]))
			{
				unset($block["revision"]);
			}
			
			if(isset($block["submit"]))
			{
				unset($block["submit"]);
			}

			$destPage->setBlockParamsById($block["blockId"], $block);
		}
		
		$destPage->setPublicationStatus("DRAFT")->setAuthor($this->getUser()->getLogin())->setLabel($formValues['label']);
		$destPage->save(false);
			
		$parent->addPage($destPage)->save();

		return $destPage;
	}
	
	private function getParent($document)
	{
		$relManager = f_relation_Manager::getInstance();

		return $relManager->getUniqueParent($document->getUniqueId(), $document->getLang());
	}
}